<?php

namespace app\common\utils;

use think\facade\Log;
use think\facade\Http;

/**
 * 地址工具类
 */
class AddressUtils
{
    // IP地址查询API
    const IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";

    // 未知地址
    const UNKNOWN = "XX XX";

    /**
     * 根据IP获取真实地址
     * @param string $ip IP地址
     * @return string
     */
    public static function getRealAddressByIP(string $ip): string
    {
        // 内网不查询
        if (IpUtils::internalIp($ip)) {
            return "内网IP";
        }

        try {
            $response = Http::get(self::IP_URL, [
                'ip' => $ip,
                'json' => 'true'
            ]);

            if (empty($response)) {
                Log::error("获取地理位置异常 {$ip}");
                return self::UNKNOWN;
            }

            $data = json_decode($response, true);
            $region = $data['pro'] ?? '';
            $city = $data['city'] ?? '';

            return trim("{$region} {$city}");

        } catch (\Exception $e) {
            Log::error("获取地理位置异常 {$ip}");
            return self::UNKNOWN;
        }
    }
}